import re
import os
from xml.etree import ElementTree
from coresales.models import Product, Photo, ProductDetail, logger
from django.contrib.sitemaps import ping_google
from coresales.models import Catalog, ProductAttribute, Category
from django.contrib.sites.models import Site
from django.contrib.flatpages.models import FlatPage
from goodsForSales.settings import MEDIA_ROOT, default_database
from robots.models import Url, Rule
from coresales.utils import maxTimeXmlFile

TO_FILL_IN = 'to fill in'
RELATIVE_PATH_PRODUCTS ="/media/products" 
PATH_SEPARATOR= "/"
ABSOLUTE_PATH_PRODUCTS= MEDIA_ROOT + 'products/'
JPG_EXTS= ".JPG"
JPEG_EXTS=".JPEG"
PREFIX_IMAGE="DSCN"
REGEX_FILE_IMAGE='DSCN[0-9]+.(JPG|JPEG)+'
EMPTY_STR=""
        
class UpdateSales:
        
        def initSite(self):
            if default_database == 'production':
                site = Site.objects.get(id=1)
                site.domain="www.todofibrofacil.com"
                site.name="http://www.todofibrofacil.com"
                site.save()
            else:
                site = Site.objects.get(id=1)
                site.domain="localhost:8000"
                site.name="http://localhost:8000"
                site.save()
            
            FlatPage.objects.all().delete()
            flatContacto= FlatPage.objects.create(url="/contact/",title="Contacto")
            flatContacto.sites.add(site)
            flatContacto.save()
            
            flatRegistar=FlatPage.objects.create(url="/accounts/register/",title="Registrarse")
            flatRegistar.sites.add(site)
            flatRegistar.save()
            
            flatLogin=FlatPage.objects.create(url="/accounts/login/",title="Login")
            flatLogin.sites.add(site)
            flatLogin.save()
            
            ProductAttribute.objects.all().delete()
            ProductAttribute.objects.create(name="Usos",description="Usos que se le pueden dar a los articulos")
            ProductAttribute.objects.create(name="Medidas",description="Medidas disponibles")
            ProductAttribute.objects.create(name="Materiales",description="Materiales utilizados para su construccion")
            
            print('Create rules robots.txt')
            Url.objects.all().delete()
            url=Url.objects.create(pattern='*')
            rule = Rule.objects.create(robot='Googlebot')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            rule = Rule.objects.create(robot='bingbot')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            rule = Rule.objects.create(robot='msnbot')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            rule = Rule.objects.create(robot='YandexBot')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            rule = Rule.objects.create(robot='facebookexternalhit')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            rule = Rule.objects.create(robot='Feedfetcher-Google')
            rule.sites=[site]
            rule.allowed=[url]
            rule.save()
            
            
            
            print "Init success"
        
        def fromProducts(self):
            pattern = re.compile(REGEX_FILE_IMAGE)
            print('Delete all products')
            Product.objects.all().delete()
            ProductDetail.objects.all().delete()
            Photo.objects.all().delete()
            for (root, dirs, files) in os.walk(ABSOLUTE_PATH_PRODUCTS):
                for file in files:
                    logger.info(' file to update ' + file)
                    if file.endswith(JPG_EXTS) or file.endswith(JPEG_EXTS):
                        code = pattern.match(file).group().replace(PREFIX_IMAGE,EMPTY_STR).replace(JPG_EXTS,EMPTY_STR).replace(JPEG_EXTS,EMPTY_STR)
                        #Create catalog if not exists.
                        catalog=root.replace(ABSOLUTE_PATH_PRODUCTS,EMPTY_STR).split(PATH_SEPARATOR)[0]
                        catalogs=Catalog.objects.filter(name=catalog)
                        if not catalogs:
                            logger.info(' new catalog ')
                            Catalog.objects.create(name=catalog,displayToolTip=catalog)
                        #Create category if not exists.
                        category =updateCategory(root, catalog)
                        #Create photo
                        relative_path = "products" + PATH_SEPARATOR + catalog + PATH_SEPARATOR + category.name
                        logger.info(' new photo ')
                        photo=Photo.objects.create(relativePath=relative_path,title=TO_FILL_IN,description=TO_FILL_IN)
                        photo.image=relative_path + PATH_SEPARATOR +file
                        photo.save()
                        #Create product
                        logger.info(' new product ')
                        product= Product.objects.create(code=code,name=file,
                                                     description=file,
                                                     category=category,
                                                     price=1.0,
                                                     costPrice=1.0,
                                                     photo=photo,
                                                     lastPublication=False,
                                                     countOfVisitors=0)
                        #Create Details
                        for attribute in ProductAttribute.objects.all():
                            ProductDetail.objects.create(product=product,value=TO_FILL_IN,description=TO_FILL_IN,attribute=attribute)
                      
                            
                    print root.replace(ABSOLUTE_PATH_PRODUCTS,EMPTY_STR) + "-" + file
        
        def getLastXmlFile(self):
            files = [f for f in os.listdir(MEDIA_ROOT +'products') if re.match(r'products+.*\.xml', f)]
            xmlFile= maxTimeXmlFile(files,0,0,'NO_FILE',MEDIA_ROOT +'products/')
            print "xml used %s" % xmlFile
            return MEDIA_ROOT + 'products/'+ xmlFile
        
        def fromXml(self):
            document = ElementTree.parse(self.getLastXmlFile())
            for product in document.findall('product'):
                #print '----------------------------------'
                #print '{:>15}: {:<30} '.format(product.tag, product.attrib['code'] + "/Price:" +product.attrib['price']) 
                productEntity=Product.objects.get(code=product.attrib['code'])
                productEntity.name=product.attrib['name']
                productEntity.description=product.attrib['name']
                productEntity.costPrice=product.attrib['price']
                if product.attrib['lastPublication'] == "True":
                    productEntity.lastPublication= True
                productEntity.countOfVisitors = product.attrib['countOfVisitors']
                productEntity.public=True
                productEntity.save()
                
                photo = product.find('./photo')
                #print '{:>15}: {:<30} '.format(photo.tag, photo.attrib['title'] + "/Description:" + photo.attrib['description']) 
                photoEntity=Photo.objects.get(image=productEntity.photo.image)
                photoEntity.title=photo.attrib['title']
                photoEntity.description=photo.attrib['description']
                photoEntity.save()
                for attribute in product.findall('.//attributes/attribute'):
                    #print '{:>15}: {:<30} '.format(attribute.tag, attribute.attrib['name'] + "/Value:" + attribute.attrib['value']) 
                    ProductDetail.objects.filter(product=productEntity,attribute__name=attribute.attrib['name']).update(value= attribute.attrib['value'],description="")
                
            
def updateCategory(root, catalog):
    category = root.replace(ABSOLUTE_PATH_PRODUCTS, EMPTY_STR).split(PATH_SEPARATOR)[1]
    categories = Category.objects.filter(name=category)
    if not categories:
        logger.info(' new category ')
        return Category.objects.create(name=category, catalog=Catalog.objects.get(name=catalog))
    else:
        return categories[0]


if __name__ == '__main__':
    
    updateSales=UpdateSales()
    updateSales.fromProducts()
    updateSales.fromXml()
    #ping_google()
    pass